
const Promise = require('bluebird');
const db = require('../model/gpwsDev');
const Theme = db.Theme;
const Stock = db.Stock;
const Logger = global.Logger('cache');

//  将数据查出来放进内存中
let themes = {};
let stocks = {};

function LoadStockAndTheme() {
    this.themeAndStock = {};
}

/**
 * 从db里面拉取数据,绘制数据
 */
LoadStockAndTheme.prototype.draw = function (code, type) {

    let model;
    if (type === 'theme') {
        model = Theme
    }
    if (type === 'stock') {
        model = Stock
    }
    return model.findOne({
        iCode: code
    })
        .then((data)=> {
            this.themeAndStock[code] = data;
            return this.themeAndStock[code];
        })
        .catch((err)=> {
            Logger.error(err);
            throw new Error('查询信息失败');
        })
};

/**
 * 暴露给外部
 * @param code  编码
 * @param type  类型
 */
LoadStockAndTheme.prototype.extract = function (code, type) {
    //  没有就查一遍并初始化数据
    if (!this.themeAndStock[code]) {
        return this.draw(code, type)
    }
    //  有就直接返回
    return Promise.resolve(this.themeAndStock[code])
};


/**
 * 提取多个code码
 * @param codes 编码
 * @param type 类型
 */
LoadStockAndTheme.prototype.extractMany = function (codes, type) {

};

/**
 * 初始化所有的数据
 */
LoadStockAndTheme.prototype.init = function () {
    //fixme 是否初始化的时候加进去这一块的数据
};

module.exports = new LoadStockAndTheme();
